import axios, {type AxiosResponse} from "axios";
import {redirect} from "react-router";

const requestApi = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000,
});

requestApi.interceptors.response.use(config => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    const token = config.headers.get('X-Authorization');
    if (token) {
        sessionStorage.setItem('X-Authorization', token);
    }

    if(config.status !== 200) {
        redirect('/');
    }

    return config;
})

requestApi.interceptors.request.use(config => {
    const token = sessionStorage.getItem('X-Authorization');
    if (!config.url?.includes("/login") && !token) {
        redirect('/');
        return config;
    }
    if (token) {
        config.headers.set('X-Authorization', token);
    }
    return config;
})


export {requestApi};

export interface Response<T> {
    headers: object,
    body: T,
    statusCodeValue: number,
    statusCode: string
}

export type ResponseBody<T> = Promise<AxiosResponse<Response<T>>>
export interface HasIdProperty {
    id: number;
}
